# -*- coding: utf-8 -*-

import sys, os, shutil
from pylot.core import Path

def printModelsAndTests(testdir):
  u"""Fonction pour afficher les tests pour chaque directory model"""
  models = {}
  for mod in testdir.listdir():
    if mod.isdir():
      modname = mod.split(u'/')[-1]
      if modname[0] != u'.':
        models[modname] = []
        for test in mod.listdir():
          testname = test.split(u'/')[-1]
          if testname[0] != u'.':
            models[modname].append(testname)
  for mod in models:
    print mod, u'\t ---> \t', models[mod]

def prepareDirectories(parameters, paramfilename, pathbook, manager):
  # tester si model/application directory exist
  print u'paramfilename=', paramfilename
  application = parameters[u"Problem"][u"application"].value
  fem = parameters[u"Problem"][u"fem"].value
  test = paramfilename.split(u'/')[-2]
  model = paramfilename.split(u'/')[-3]
  basedir = u'/'.join(paramfilename.split(u'/')[0:-3])
  testdir = u'/'.join(paramfilename.split(u'/')[0:-1])
  print u'application model basedir testdir = ', application, model, basedir, testdir

  if not paramfilename.isfile() :
    print u"@@@pythonERROR in prepareDirectories(): no such file \"", paramfilename
    sys.exit(1)

  run_dir = pathbook(u'project', u'test', u'RunResults', model, test, u'Run')
  if not run_dir.exists() :
    run_dir.makedirs()

  # Préparation paramfile
  parmfilein = Path(basedir, u"Run.pylotparam")
  applicationfile = Path(testdir, u"Application.pylotparam")
  if not applicationfile.exists() :
    print u'@@@pythonERROR in prepareDirectories(): cannot open file \'', applicationfile, u'\''
    sys.exit(1)

  manager.parameters.clear()
  manager.parameters.readParameters(parmfilein)
  manager.parameters.readParameters(applicationfile)
  manager.parameters.saveParameters()

  return run_dir


def createUniformMesh(parameters, mesh, meshout, nlevels, pathbook, manager):
  # Création du maillage
  meshin = pathbook(u'meshresources', u'quad_resources', mesh)
  datatype = parameters[u"Problem"][u"datatype"].value

  executable = pathbook(u'bin', u'MeshReaders', u'ReaderQuad')
  args = [meshin, meshout, datatype]
  # from pylot.tool import CommandGroup
  # process_handler.stdout = CommandGroup.OutputVars
  cg = manager.runCmd(cmd=executable, args=args)

  # cg.shellcmds[0].stdout

  executable = pathbook(u'bin', u'MeshTools', u'pyLotMeshUniformRefiner')
  args = [meshout, meshout, unicode(nlevels)]
  cg = manager.runCmd(cmd=executable, args=args)

  tri = u"no"
  if parameters.checkHasDatum(u"AdaptiveAlgorithm", u"quadtotri") :
    tri = parameters[u"AdaptiveAlgorithm"][u"quadtotri"].value
  if tri == u"yes":
    executable = pathbook(u'bin', u'MeshTools', u'QuadMeshToTriangleMesh')
    args = [meshout, meshout, u"crisscross", datatype]
    cg = manager.runCmd(cmd=executable, args=args)
    if cg.return_code != 0 :
      print u'$$$  commande \"', executable, u'\" n\'a pas marché !!!'
      sys.exit(1)

  executable = pathbook(u'bin', u'MeshTools', u'CreateNormals')
  args = [meshout]
  cg = manager.runCmd(cmd=executable, args=args)
